package net.streaming.rtsp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpStream extends Stream {
	private DatagramSocket socket;
	private DatagramPacket packet;
	
	private MyByteArrayOutputStream baos;
	
	public UdpStream(InputStream source) throws IOException {
		super(source);
		baos = new MyByteArrayOutputStream(MTU);
		this.setOut(baos);
		
		socket = new DatagramSocket();
		packet = new DatagramPacket(baos.getBuffer(), 0);
	}
	
	public void sendStream() throws IOException{
		this.traveNalus(this);
	}
	
	public void setDest(String ip, int dport) throws IOException{
		packet.setAddress(InetAddress.getByName(ip));
		packet.setPort(dport);		
	}
	
	private void send(int length) throws IOException{
		if(length>MTU){
			System.out.println(length);
		}
		packet.setLength(length);
		socket.send(packet);
	}
	
	public boolean handle(byte[] nal_buf, int nal_len) {
		try {
			writeNalu(nal_buf, nal_len, false);
			Thread.sleep(40);
		} catch (IOException e) {
			e.printStackTrace();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return true;
		}
		return false;
	}

	public Object getResult() {
		return null;
	}

	class MyByteArrayOutputStream extends ByteArrayOutputStream{

		public MyByteArrayOutputStream(int size) {
			super(size);
		}

		public byte[] getBuffer(){
			return this.buf;
		}
		
	    public void flush() throws IOException {
	    	send(this.size());
	    	this.reset();
	    }
	}
	
}
